<template>
  <div class="bg">
    <el-row>
      <el-col :span="4" :offset="8">
        <p>
          <el-button
            type="primary"
            style="
              background-color: #0d9c98;
              border-color: #0d9c98;
              width: 150px;
            "
            @click="toWrite"
            size="small"
            class="buttonSet2 buttonFontSize"
            >我要写信</el-button
          >
        </p>
      </el-col>
      <el-col :span="4">
        <p>
          <el-button
            type="primary"
            style="background-color: #0d4d9c; border-color: #0d4d9c"
            @click="toList"
            size="small"
            class="buttonSet2 buttonFontSize"
          >
            查看信件列表
            <span style="color: #dcca16">({{ mail_count }}条)</span>
          </el-button>
        </p>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-blue">
          <el-row>
            <el-col :span="6"
              ><span class="textFontSize"
                >发信人:&nbsp;&nbsp;{{ sender }}</span
              ></el-col
            >
            <el-col :span="4"
              ><span class="textFontSize"
                >接收人:&nbsp;&nbsp;总经理</span
              ></el-col
            >
            <el-col :span="6" :offset="2"
              ><span class="textFontSize"
                >发布时间:&nbsp;&nbsp;{{ sendTime }}</span
              ></el-col
            >
          </el-row>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-gray">
          <el-row>
            <el-col :span="4"
              ><span class="textFontSize">问题内容:</span></el-col
            >
          </el-row>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-content">
          <el-row>
            <el-col>
              <div class="cover" v-html="sendContent"></div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>

    <el-row
      v-for="reply in replyList"
      :key="reply.uuid"
      style="margin-top: 20px"
    >
      <el-col :span="24">
        <div class="grid-content bg-blue">
          <el-row>
            <el-col :span="6"
              ><span class="textFontSize"
                >发送人:&nbsp;&nbsp;{{ reply.replyUser }}</span
              ></el-col
            >
            <el-col :span="4"
              ><span class="textFontSize"
                >接收人:&nbsp;&nbsp;{{ reply.replyToName }}</span
              ></el-col
            >
            <el-col :span="6" :offset="2"
              ><span class="textFontSize"
                >发送时间:&nbsp;&nbsp;{{ reply.replyTime }}</span
              ></el-col
            >
          </el-row>
        </div>
      </el-col>

      <el-col :span="24">
        <div class="grid-content bg-gray">
          <el-row>
            <el-col :span="4"
              ><span class="textFontSize">回信内容:</span></el-col
            >
          </el-row>
        </div>
      </el-col>

      <el-col :span="24">
        <div class="grid-content bg-content">
          <el-row>
            <el-col :span="18">
              <div class="cover" v-html="reply.content"></div>
            </el-col>
            <el-col
              :span="6"
              v-if="
                reply.replyId !== null && reply.mailBoxReplyFileJsons.length > 0
              "
            >
              <div style="background-color: #D7D7D7">
                <div>附件列表:</div>
                <div>
                  <ul>
                    <li
                      v-for="file in reply.mailBoxReplyFileJsons"
                      :key="file.replyFileId"
                    >
                      <a
                        :href="downloadUrl + file.replyFileId"
                        target="_blank"
                        >{{ file.replyFileName }}</a
                      >
                    </li>
                  </ul>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>

    <div v-if="mail.role === '发信人'">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-gray" style="background-color: #fafafa">
            <el-row>
              <el-col :span="4"
                ><span class="textFontSize">问题是否已经解决:</span></el-col
              >
              <el-col :span="6">

                <el-radio v-model="isSolved" label="1"
                  ><span class="textFontSize">是</span></el-radio
                >
                <el-radio v-model="isSolved" label="0" v-if="!solvable"
                  ><span class="textFontSize">否</span></el-radio
                >
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-row v-show="isSolved === '0'">
        <el-col :span="24">
          <div>
            <el-row class="grid-content bg-blue">
              <el-col :span="4"
                ><span class="textFontSize">追加留言:</span></el-col
              >
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form
                  ref="ruleForm"
                  label-width="100px"
                  style="margin-top: 20px"
                >
                  <el-form-item>
                    <template #label>
                      <span class="textFontSize">问题内容:</span>
                    </template>

                    <!-- 20201010 添加富文本编辑器 -->
                    <div id="wangBackEditorElement"></div>
                  </el-form-item>
                  <el-form-item>
                    <template #label>
                      <span class="textFontSize">附件:</span>
                    </template>
                    <el-upload
                      class="upload-demo"
                      ref="upload"
                      multiple
                      action
                      :show-file-list="false"
                      :on-change="handleChange"
                      :file-list="fileList"
                      :auto-upload="false"
                      accept=".pdf,.doc,.docx,.xlsx,.xls,.ppt,.pptx,.png,.jpg,.jpeg,.wps,.txt,.wmv,.mov,.avi,.wm,.mp3,.wav"
                    >
                      <el-button
                        style="
                          background-color: #a2b2be;
                          color: white;
                          border-color: #a2b2be;
                        "
                        slot="trigger"
                        size="small"
                        type="primary"
                        class="buttonSet2 buttonFontSize"
                        >选取文件</el-button
                      >
                      <div
                        slot="tip"
                        class="el-upload__tip"
                        v-for="file in this.fileList"
                        :key="file.name"
                      >
                        {{ file.name }}
                        <i
                          @click="deleteFile(file)"
                          style="margin-left: 20px"
                          class="el-icon-delete"
                        ></i>
                      </div>
                    </el-upload>
                  </el-form-item>

                  <el-form-item>
                    <span style="color: #9f9f9f" class="textFontSize"
                      >*（支持上传ppt，excel，word，pdf，图片格式的附件，文件大小低于50兆）</span
                    >
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-row v-if="!solvable">
        <el-col :span="3" :offset="8">
          <p>
            <el-button
              type="primary"
              style="background-color: #0e4d9d; border-color: #0e4d9d"
              @click="submit()"
              :disabled="solvable"
              class="buttonSet2 buttonFontSize"
              >提交</el-button
            >
          </p>
        </el-col>
        <el-col :span="3" :offset="2">
          <p>
            <el-button
              type="primary"
              style="background-color: #a1b3bf; border-color: #a1b3bf"
              @click="reset()"
              v-loading.fullscreen.lock="fullscreenLoading"
              class="buttonSet2 buttonFontSize"
              >取消</el-button
            >
          </p>
        </el-col>
      </el-row>
    </div>

    <div v-if="mail.role === '承办人'">
      <el-row v-show="replyShow">
        <el-col :span="24">
          <el-row class="grid-content bg-blue">
            <el-col :span="4"
              ><span class="textFontSize">{{replyText}}</span></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form
                ref="ruleForm"
                label-width="100px"
                style="margin-top: 20px"
              >
                <el-form-item>
                  <template #label>
                    <span class="textFontSize">回复内容:</span>
                  </template>

                  <el-input
                    type="textarea"
                    placeholder="请在此输入您的正文内容..."
                    v-model="addContent"
                    maxlength="1000"
                    :autosize="{ minRows: 6, maxRows: 12 }"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3" :offset="8">
          <p>
            <el-button
              v-show="!replyShow"
              type="primary"
              style="background-color: #199BD6; border-color: #199BD6"
              @click="showReply()"
              :disabled="solvable"
              class="buttonSet2 buttonFontSize"
              >回复总经理</el-button
            >

            <el-button
              v-show="replyShow"
              type="primary"
              style="background-color: #0e4d9d; border-color: #0e4d9d"
              @click="submit()"
              :disabled="solvable"
              class="buttonSet2 buttonFontSize"
              >提交</el-button
            >
          </p>
        </el-col>
        <el-col :span="3" :offset="2">
          <p>
            <el-button
              type="primary"
              style="background-color: #a1b3bf; border-color: #a1b3bf"
              @click="resetReply()"
              v-loading.fullscreen.lock="fullscreenLoading"
              class="buttonSet2 buttonFontSize"
              >取消</el-button
            >
          </p>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { Api } from "../api/api_config";
import uuidv1 from "uuid/v1";
import E from "wangeditor";

export default {
  data() {
    return {
      sender: "",
      sendTime: "",
      replyer: "",
      isSolved: "1",
      sendContent: "",
      replyContent: "",
      addContent: "",
      replyTime: "",
      formData: "",
      empId: "",
      // 信件实体
      mail: {},
      fullscreenLoading: false,
      replyList: [],
      solvable: false,
      fileList: [],
      mail_count: 0,
      file_size: 0,
      filterExt: [
        "pdf",
        "doc",
        "docx",
        "xlsx",
        "xls",
        "ppt",
        "pptx",
        "png",
        "jpg",
        "jpeg",
        "wps",
        "txt",
        "wmv",
        "mov",
        "avi",
        "wm",
        "mp3",
        "wav",
      ],
      editor: {},
      // 2020 10 20 添加，默认3
      replyShow: false,
      downloadUrl: "",
      replyText: '追加留言:'
    };
  },
  created() {
    this.initData();
  },
  mounted() {
    this.editor = new E("#wangBackEditorElement");
    this.editor.config.menus = [
      "head",
      "bold",
      "fontSize",
      "italic",
      "underline",
      "strikeThrough",
      "indent",
      "lineHeight",
      "foreColor",
      "backColor",
      "link",
      "list",
      "justify",
      "splitLine",
      "undo",
      "redo",
    ];
    this.editor.create();
  },
  methods: {
    initData() {
      this.mail = this.$store.state.selectedMail;
      this.sender = this.mail.senderName;
      this.sendTime = this.mail.createTime;
      this.sendContent = this.mail.content;
      this.empId = this.$store.state.empId;
      this.formData = new FormData();
      this.queryReplyMail(this.mail.senderEmpId, this.mail.id);
      if (this.mail.isSolved === "1" || this.mail.isSolved === 1) {
        this.solvable = true;
      } else {
        this.solvable = false;
      }

      if (this.mail.role === "发信人") {
        this.replyText = '追加留言:'
      }
      if (this.mail.role === "承办人") {
        this.replyText = '回复总经理:'
      }

      this.downloadUrl = Api.all.download + "?fileId=";

      this.queryMails();
    },
    v_upload_files(e) {
      let files = e.target.files;
      this.formData = new FormData();
      for (let i = 0; i < files.length; i++) {
        this.formData.append("files", files[i]);
      }
    },
    submit() {
      let that = this;

      let url = "";

      if (this.mail.role === "发信人") {
        this.addContent = this.editor.txt.html();
        if (this.isSolved !== '1') {
          let text = this.addContent.replace(/<[^<>]+>/g, "");
          if (text.length <= 10) {
            this.$message({
              message: "您提交的信息太少，请至少输入10个字，详细描述后提交",
              type: "warning",
            });
            return;
          }

          if (text.length > 1000) {
            this.$message({
              message: "您提交文字内容已经大于1000字，请检查后提交",
              type: "warning",
            });
            return;
          }
        }


        url =
          Api.all.replyMail +
          "?isPc=true&id=" +
          this.mail.id +
          "&replyBy=" +
          // this.mail.senderEmpId +
          this.empId +
          "&replyFlag=3" +
          "&isSolved=" +
          this.isSolved +
          "&replyTo=00011";
      }

      if (this.mail.role === "承办人") {
        if (this.addContent.length <= 10) {
          this.$message({
            message: "您提交的信息太少，请至少输入10个字，详细描述后提交",
            type: "warning",
          });
          return;
        }

        if (this.addContent.length > 1000) {
          this.$message({
            message: "您提交文字内容已经大于1000字，请检查后提交",
            type: "warning",
          });
          return;
        }

        url =
          Api.all.replyMail +
          "?&id=" +
          this.mail.id +
          "&replyBy=" +
          // this.mail.senderEmpId +
          this.empId +
          "&replyFlag=4" +
          "&replyTo=00011";
      }

      this.formData = new FormData();
      // formData重复的往一个值添加数据并不会被覆盖掉，可以全部接收到，可以通过formData.getAll('files')来查看所有插入的数据
      for (let i = 0; i < this.fileList.length; i++) {
        this.formData.append("files", this.fileList[i].raw);
      }

      this.formData.append("content", this.addContent);

      this.fullscreenLoading = true;
      this.$axios
        .post(url, this.formData)
        .then(function (response) {
          // console.log(response.data);
          if (response.data !== null) {
            that.$message({
              message: "提交信息成功",
              type: "success",
            });
          }
          if (that.mail.role === "发信人") {
            that.reset();
          } else {
            that.resetReply();
          }

          that.fullscreenLoading = false;
        })
        .catch(function (error) {
          console.log(error);
          that.$message.error("数据有误");
          that.fullscreenLoading = false;
        });
    },
    reset() {
      this.addContent = "";
      // document.getElementById('upload_file_detail').value = '';
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.$router.push("/mailList");
    },
    queryReplyMail(empId, id) {
      let that = this;
      let url = Api.all.queryReplyMails + "";
      url += "?currentUserEmpId=" + this.empId;
      url += "&empId=" + empId;
      url += "&id=" + id;

      this.$axios
        .post(url)
        .then(function (response) {
          // console.log(response.data);
          if (response.data !== null) {
            let list = response.data.data.mailBoxReplyJson;
            let tempList = [];
            for (let i = 0; i < list.length; i++) {
              const element = list[i];
              // 20201009 将 replyUserEmpId = 00011 的都显示
              // 20201020 修改为不做过滤
              // if ((element.replyUserEmpId === "00011" && element.replyTo === that.empId) || (element.replyUserEmpId === that.empId && element.replyTo === "00011")) {
              //   element["uuid"] = uuidv1();
              //   tempList.push(element);
              // }
              // 20201020 当replyId为null 显示已转发xxx
              if (element.replyId === null) {
                // element.content = '已转发' + element.forwardName + '处理。'
                continue;
              }
              element["uuid"] = uuidv1();
              tempList.push(element);
            }
            that.replyList = tempList;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleChange(file, fileList) {
      // 判断文件不能大于50M
      let isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        this.$message({
          message: "您提交的文件太大，文件不能高于50M，请重新选择附件。",
          type: "warning",
        });
      }

      // 判断文件类型
      let ext = file.name.substring(file.name.lastIndexOf(".") + 1);
      let isAllowExt = false;
      this.filterExt.forEach((element) => {
        if (element === ext) {
          isAllowExt = true;
        }
      });

      if (!isAllowExt) {
        this.$message({
          message: "您提交的文件不在允许的范围内。",
          type: "warning",
        });
        return;
      }

      let isOverMax = this.file_size + file.size > 1024 * 1024 * 100;
      if (isOverMax) {
        this.$message({
          message: "您提交的文件一共大小超过了100M，请重新选择附件。",
          type: "warning",
        });
        return;
      }

      if (file !== null || file !== undefined) {
        this.file_size = this.file_size + file.size;
        this.fileList.push(file);
      }
    },
    deleteFile(item) {
      this.fileList.splice(
        this.fileList.findIndex((e) => e.uid === item.uid),
        1
      );
      this.file_size = this.file_size - item.size;
    },
    toWrite() {
      this.$router.push("/newMail");
    },
    toList() {
      this.$router.push("/mailList");
    },
    queryMails() {
      // 拼接查询参数
      let url = Api.all.queryMails;
      url += "?empId=" + this.empId;
      url += "&mailboxStatusFlag=104";
      url += "&pageNum=" + 1;
      url += "&pageSize=" + 5;
      // url += "&isPc=true";
      let that = this;
      this.$axios
        .post(url)
        .then(function (response) {
          if (response.data !== null) {
            that.mail_count = response.data.data.totalCount;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 20201109
    showReply() {
      this.replyShow = true;
    },
    resetReply() {
      this.$router.push("/mailList");
    },
  },
};
</script>

<style scoped>
.grid-content {
  min-height: 36px;
}
.bg-blue {
  background: #387fcf;
  line-height: 60px;
  padding-left: 20px;
  color: white;
  font-size: 14px;
  font-weight: bold;
}
.bg-gray {
  background: #e1e5ee;
  line-height: 60px;
  padding-left: 20px;
  color: #3a3e41;
  font-size: 14px;
  font-weight: bold;
}
.bg-content {
  padding-left: 20px;
  color: #3a3a3a;
  padding-top: 20px;
}
.cover {
  width: 100%;
  height: auto;
  border-radius: 10px;
  background-size: 100% auto;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
}

.bg {
  filter: progid:DXImageTransform.Microsoft.Shadow(color=#909090,direction=120,strength=4); /*ie*/
  -moz-box-shadow: 2px 2px 10px #909090; /*firefox*/
  -webkit-box-shadow: 2px 2px 10px #909090; /*safari或chrome*/
  box-shadow: 2px 2px 10px #909090; /*opera或ie9*/
  border: 1px soild #ccc;
  border-radius: 10px;
  -webkit-border-radius: 9px;
  -moz-border-radius: 9px;
  background-color: white;
  padding: 10px 10px 10px 10px;
}

ul {
  list-style: none;
}
</style>
